﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MasterDatail {
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        System.ComponentModel.BackgroundWorker bw;
        public delegate int delegado();

        
        public MainWindow() {
         

            bw = new System.ComponentModel.BackgroundWorker();

            bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;
            bw.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(bw_ProgressChanged);
        
            
        }

        private int miMetodo() {

            int i = 0;
            System.IO.StreamWriter sw = new System.IO.StreamWriter("c://t.csv", true);
            while (i < 200) {
                sw.Write(i.ToString() + ";");
                i++;
                System.Threading.Thread.Sleep(100);
            }
             sw.Close();
            return i;
        }


        void bw_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) {

            l1.Content = e.ProgressPercentage;
        }

        void bw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) {
            try {
                MessageBox.Show(e.Cancelled.ToString() );
                MessageBox.Show(e.Result.ToString());
            } catch (Exception ex) { 
            
            }
            }

        private delegate void cambiaControl(object str);

        void cambiaboton(object str) {

            if (str.GetType().Equals(typeof(Button))) {

                bc.Content = str;
                MessageBox.Show("bUTTON :"+System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());

            } else { ((Button)bc.Content).Content = str;
            MessageBox.Show("String :" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());

            }
        
        }
        
        void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
            int i=0;
            System.IO.StreamWriter sw = new System.IO.StreamWriter(e.Argument.ToString(), true);
            MessageBox.Show("BCKW: "+System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
            DatePicker DP = new DatePicker();
            Button boton = new Button();
            
            boton.Name = "btn";
            boton.Content = "NEW";
            
            bc.Dispatcher.BeginInvoke(new cambiaControl(cambiaboton), System.Windows.Threading.DispatcherPriority.Background, boton);
            while (i < 4) {
                e.Result = i;
                if (bw.CancellationPending) {
                    e.Cancel = true;
                    break;
                }
                sw.Write(i.ToString()+";");
                i++;
                System.Threading.Thread.Sleep(500);
                bw.ReportProgress((int)(i * 0.5));

            }
            boton.Dispatcher.BeginInvoke(new cambiaControl(cambiaboton),"Cambiado");

            sw.Close();

        }

        private void Window_Loaded(object sender, RoutedEventArgs e) {



            MasterDatail.NwindDataSet nwindDataSet = ((MasterDatail.NwindDataSet)(this.FindResource("nwindDataSet")));
            // Cargar datos en la tabla Products. Puede modificar este código según sea necesario.
            MasterDatail.NwindDataSetTableAdapters.ProductsTableAdapter nwindDataSetProductsTableAdapter = new MasterDatail.NwindDataSetTableAdapters.ProductsTableAdapter();
            nwindDataSetProductsTableAdapter.Fill(nwindDataSet.Products);
            System.Windows.Data.CollectionViewSource productsViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("productsViewSource")));
            productsViewSource.View.MoveCurrentToFirst();
           // productsViewSource.GroupDescriptions.Add(new PropertyGroupDescription("CategoryID"));
            //productsViewSource.GroupDescriptions.Add(new PropertyGroupDescription("UnitPrice",new MGroup()));
            ((BindingListCollectionView)productsViewSource.View).CustomFilter = "UnitPrice >50";
          

            List<string> L = new List<string>();
            L.Add("a");
            L.Add("b");
            L.Add("c");
            ListCollectionView lcv=(ListCollectionView) CollectionViewSource.GetDefaultView(L);
            lcv.CustomSort = new COrder();
            

           lcv.Filter = new Predicate<object>(filtro); 
            ll.ItemsSource = lcv;



        }

        public bool filtro(object o) {
           
            return true;
        }

        private void Button_Click(object sender, RoutedEventArgs e) {

            MessageBox.Show("UI :"+System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
            if (!bw.IsBusy)
            bw.RunWorkerAsync("c://t.csv");
         //   delegado d = new delegado(miMetodo);
          //  IAsyncResult Ar;
            

           //Ar= d.BeginInvoke(new AsyncCallback(MCB),d);
        
            
        
        }

        private void MCB(IAsyncResult R) {
            delegado d;
            d = (delegado)R.AsyncState;
            MessageBox.Show(d.EndInvoke(R).ToString());
        }

        private void Button_Click_1(object sender, RoutedEventArgs e) {
            bw.CancelAsync();
        }

        private void TextBox_MouseDown(object sender, MouseButtonEventArgs e) {
            MessageBox.Show("asfassf");
        }

      

      

    }

    public class Calc {

        public String m(int a, int b) {
            return (a + b).ToString();
        }
    
    }

    public class CatToColor : IValueConverter {


        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            int cat = (int)value;
            if (cat == 2) {
                return new SolidColorBrush(Colors.Orange);

            } else return new SolidColorBrush(Colors.Green);

        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            throw new NotImplementedException();
        }
    }

    public class Select : DataTemplateSelector {
        public override DataTemplate SelectTemplate(object item, DependencyObject container) {
            System.Data.DataRowView drv;
            FrameworkElement fe = (FrameworkElement)container;
            if (fe != null && item != null && item is System.Data.DataRowView) {
                drv = (System.Data.DataRowView)item;
                object obj = drv["UnitPrice"];
                double d = Double.Parse(obj.ToString());
                if (d > 20)

                    return (DataTemplate)fe.FindResource("dt2");
                else
                    return (DataTemplate)fe.FindResource("dt1");

            }

            return (DataTemplate)fe.FindResource("dt1");

        }

    }


    public class COrder : System.Collections.IComparer{

public int Compare(object x, object y) {
    return ((string)x).CompareTo(y)*-1;
        }


    }


    public class MGroup : IValueConverter {


        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {

     

         
            double d = Double.Parse(value.ToString());
            if (d > 20) {
                return "Caro";
            } else
                return "Barato";
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            throw new NotImplementedException();
        }
    }


    public class Person:  DependencyObject,System.ComponentModel.IDataErrorInfo {

        public static DependencyProperty NombreProperty;
        public static DependencyProperty ApellidoProperty;

        public string Nombre {
            get { return (string)this.GetValue(Person.NombreProperty);  }
            set { this.SetValue(NombreProperty, value); }
        }

        public string Apellido {
            get { return (string)this.GetValue( Person.ApellidoProperty); }
            set { this.SetValue(ApellidoProperty, value); }
        }

        static  Person() {
          NombreProperty=  DependencyProperty.Register("Nombre",typeof(string),typeof(Person));
          ApellidoProperty=  DependencyProperty.Register("Apellido", typeof(string), typeof(Person));
           
        }

        public string Error {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName] {
            get {
                if (columnName == "Nombre")
                    if (Nombre == "jose")
                        return "Jose no es pERMITIDO";
                return null;
            
            }
        }
    }


}
